package com.sanbi.erp.db.service;

import com.github.pagehelper.PageHelper;
import com.sanbi.common.util.JacksonUtil;
import com.sanbi.erp.core.system.Enums;
import com.sanbi.erp.core.util.Generator;
import com.sanbi.erp.core.util.ProcurementPlanUtils;
import com.sanbi.erp.core.util.TypeStateUtil;
import com.sanbi.erp.db.dao.ProcurementPlanMapper;
import com.sanbi.erp.db.dao.ProductMapper;
import com.sanbi.erp.db.domain.*;
import com.sanbi.erp.db.util.CheckoutUtil;
import com.sanbi.erp.db.util.IpUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
public class ProcurementPlanService{

    @Resource
    private ProcurementPlanMapper procurementPlanMapper;
    @Resource
    private AdminService adminService;
    @Resource
    private LogService logService;
    @Resource
    private ProductMapper productMapper;

    
    public int deleteByPrimaryKey(Integer id) {
        return procurementPlanMapper.deleteByPrimaryKey(id);
    }

    
    public int insert(ProcurementPlan record) {
        return procurementPlanMapper.insert(record);
    }

    
    public int insertSelective(ProcurementPlan record) {
        return procurementPlanMapper.insertSelective(record);
    }

    /**
     * 创建采购计划
     * @param adminId 当前管理员id
     * @param list 采购计划集合
     * @return
     */
    public int addList(Integer adminId,List<ProcurementPlan> list) {
        for (ProcurementPlan procurementPlan : list) {
            procurementPlan.setProcurementPlanSn(Generator.createObjectSn(Enums.ObjectType.ProcurementPlanSn)); // 编号
            procurementPlan.setProcurementPlanAdminId(adminId); // 用户id
            procurementPlan.setProcurementPlanState(ProcurementPlanUtils.P_STATE_ONE);
            procurementPlan.setAddTime(LocalDateTime.now());
            procurementPlan.setUpdateTime(LocalDateTime.now());
            procurementPlan.setDeleted(false);
        }
        return procurementPlanMapper.insertSelectiveList(list);
    }

    public ProcurementPlan selectByPrimaryKey(Integer id) {
        return procurementPlanMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取采购计划信息
     * @param body 查询条件
     * {matching  0 默认 1 精确匹配 2 模糊匹配,
     *  detailsType 0 默认 1 库存sku 3 中文名称 5 供应商,
     *  message 查询内容,
     *  planState sku状态 0 全部 1001 待审核，1002 同意，1003 拒绝
     *  beginTime 开始时间
     *  endTime 结束时间
     *  page 页索引
     *  limit 页大小}
     * @return
     */
    public List<ProcurementPlan> selectLinkList(String body, Integer page, Integer limit) {
        Integer matching = JacksonUtil.parseInteger(body, "matching");
        Integer detailsType = JacksonUtil.parseInteger(body, "detailsType");
        String message = JacksonUtil.parseString(body, "message");
        Integer planState = JacksonUtil.parseInteger(body, "planState");
        String beginTime = JacksonUtil.parseString(body, "beginTime");
        String endTime = JacksonUtil.parseString(body, "endTime");
        if (CheckoutUtil.isEmptyInteger(matching)) matching = null;
        if (CheckoutUtil.isEmptyInteger(detailsType)) detailsType = null;
        PageHelper.startPage(page,limit);
        return procurementPlanMapper.selectLinkList(matching, detailsType, message, planState,beginTime,endTime);
        // log.info("{}查询的数据：",productList);
        // return productList;
    }

    /**
     * 批量导出采购计划信息
     * @param body 查询条件
     * {matching  0 默认 1 精确匹配 2 模糊匹配,
     *  detailsType 0 默认 1 库存sku 3 中文名称 5 供应商,
     *  message 查询内容,
     *  planState sku状态 0 全部 1001 待审核，1002 同意，1003 拒绝
     *  beginTime 开始时间
     *  endTime 结束时间
     *  page 页索引
     *  limit 页大小}
     * @return
     */
    public List<ProcurementPlanEasyExcelDerive> batchDeriveExcel(String body, Integer page, Integer limit) {
        Integer matching = JacksonUtil.parseInteger(body, "matching");
        Integer detailsType = JacksonUtil.parseInteger(body, "detailsType");
        String message = JacksonUtil.parseString(body, "message");
        Integer planState = JacksonUtil.parseInteger(body, "planState");
        String beginTime = JacksonUtil.parseString(body, "beginTime");
        String endTime = JacksonUtil.parseString(body, "endTime");
        if (CheckoutUtil.isEmptyInteger(matching)) matching = null;
        if (CheckoutUtil.isEmptyInteger(detailsType)) detailsType = null;
        PageHelper.startPage(page,limit);
        List<ProcurementPlan> procurementPlanList = procurementPlanMapper.selectLinkList(matching, detailsType, message, planState, beginTime, endTime);
        // 筛选出组合商品
        List<ProcurementPlan> regionsOne = procurementPlanList.stream().filter(region -> region.getProduct().getProductIsGroup()).collect(Collectors.toList());
        // 筛选出普通商品
        List<ProcurementPlan> regionsTwo = procurementPlanList.stream().filter(region -> !region.getProduct().getProductIsGroup()).collect(Collectors.toList());
        // 存储导出数据
        List<ProcurementPlanEasyExcelDerive> list = new ArrayList<>();
        // 添加普通商品
        for (ProcurementPlan procurementPlan : regionsTwo) {
            ProcurementPlanEasyExcelDerive procurementPlanEasyExcelDerive = new ProcurementPlanEasyExcelDerive();
            procurementPlanEasyExcelDerive.setProductSku(procurementPlan.getProduct().getProductSku());
            procurementPlanEasyExcelDerive.setProductNameCn(procurementPlan.getProduct().getProductNameCn());
            procurementPlanEasyExcelDerive.setProcurementPlanCount(procurementPlan.getProcurementPlanCount());
            procurementPlanEasyExcelDerive.setPurchasePrice(procurementPlan.getProduct().getPurchasePrice());
            procurementPlanEasyExcelDerive.setProviderName(procurementPlan.getProduct().getProviderName());
            procurementPlanEasyExcelDerive.setProcurementPlanStore(procurementPlan.getProcurementPlanStore());
            procurementPlanEasyExcelDerive.setUsername(procurementPlan.getUsername());
            procurementPlanEasyExcelDerive.setProcurementPlanSn(procurementPlan.getProcurementPlanSn());
            procurementPlanEasyExcelDerive.setProcurementPlanDesc(procurementPlan.getProcurementPlanDesc());
            list.add(procurementPlanEasyExcelDerive);
        }
        // 添加组合商品
        if (regionsOne.size() > CheckoutUtil.TYPE_ZERO) {
            // 存储组合商品的sku
            List<String> listGroupSku = new ArrayList<>();
            for (ProcurementPlan procurementPlan : regionsOne) {
                listGroupSku.add(procurementPlan.getProduct().getProductSku());
            }
            // 获取组合商品信息
            List<Product> productList = this.productMapper.selectLinkListGroupBySku(listGroupSku, listGroupSku.get(CheckoutUtil.TYPE_ZERO));
            // 遍历组合商品表信息
            for (Product product : productList) {
                // 遍历组合商品的组成商品集合
                for (ProductGroup productGroup : product.getProductGroupList()) {
                    ProcurementPlanEasyExcelDerive procurementPlanEasyExcelDerive = new ProcurementPlanEasyExcelDerive();
                    procurementPlanEasyExcelDerive.setProductSku(product.getProductSku());
                    procurementPlanEasyExcelDerive.setProductSkuTwo(productGroup.getProductParentSku());
                    procurementPlanEasyExcelDerive.setProductNameCn(productGroup.getProductParentName());
                    procurementPlanEasyExcelDerive.setPurchasePrice(productGroup.getPurchasePrice());
                    procurementPlanEasyExcelDerive.setProviderName(productGroup.getProviderName());
                    // 遍历采购呢计划信息
                    for (ProcurementPlan procurementPlan : regionsOne) {
                        if (procurementPlan.getProduct().getProductSku().equals(product.getProductSku())) {
                            procurementPlanEasyExcelDerive.setProcurementPlanStore(procurementPlan.getProcurementPlanStore());
                            // 采购计划组合商品数量 = 采购数量 * 组合商品的组成商品的数量
                            procurementPlanEasyExcelDerive.setProcurementPlanCount(productGroup.getProductParentCount() * procurementPlan.getProcurementPlanCount());
                            procurementPlanEasyExcelDerive.setUsername(procurementPlan.getUsername());
                            procurementPlanEasyExcelDerive.setProcurementPlanSn(procurementPlan.getProcurementPlanSn());
                            procurementPlanEasyExcelDerive.setProcurementPlanDesc(procurementPlan.getProcurementPlanDesc());
                        }
                    }
                    list.add(procurementPlanEasyExcelDerive);
                }
            }
        }
        return list;
    }

    /**
     * 批量导出采购计划信息
     * @return
     */
    public List<ProcurementPlanEasyExcelDerive> batchDeriveExcelGroupById(List<Integer> listInteger) {
        List<ProcurementPlan> procurementPlanList = procurementPlanMapper.batchDeriveExcelGroupById(listInteger,listInteger.get(CheckoutUtil.TYPE_ZERO));
        // 筛选出组合商品
        List<ProcurementPlan> regionsOne = procurementPlanList.stream().filter(region -> region.getProduct().getProductIsGroup()).collect(Collectors.toList());
        // 筛选出普通商品
        List<ProcurementPlan> regionsTwo = procurementPlanList.stream().filter(region -> !region.getProduct().getProductIsGroup()).collect(Collectors.toList());
        // 存储导出数据
        List<ProcurementPlanEasyExcelDerive> list = new ArrayList<>();
        // 添加普通商品
        for (ProcurementPlan procurementPlan : regionsTwo) {
            ProcurementPlanEasyExcelDerive procurementPlanEasyExcelDerive = new ProcurementPlanEasyExcelDerive();
            procurementPlanEasyExcelDerive.setProductSku(procurementPlan.getProduct().getProductSku());
            procurementPlanEasyExcelDerive.setProductNameCn(procurementPlan.getProduct().getProductNameCn());
            procurementPlanEasyExcelDerive.setProcurementPlanCount(procurementPlan.getProcurementPlanCount());
            procurementPlanEasyExcelDerive.setPurchasePrice(procurementPlan.getProduct().getPurchasePrice());
            procurementPlanEasyExcelDerive.setProviderName(procurementPlan.getProduct().getProviderName());
            procurementPlanEasyExcelDerive.setProcurementPlanStore(procurementPlan.getProcurementPlanStore());
            procurementPlanEasyExcelDerive.setUsername(procurementPlan.getUsername());
            procurementPlanEasyExcelDerive.setProcurementPlanSn(procurementPlan.getProcurementPlanSn());
            procurementPlanEasyExcelDerive.setProcurementPlanDesc(procurementPlan.getProcurementPlanDesc());
            list.add(procurementPlanEasyExcelDerive);
        }
        // 添加组合商品
        if (regionsOne.size() > CheckoutUtil.TYPE_ZERO) {
            // 存储组合商品的sku
            List<String> listGroupSku = new ArrayList<>();
            for (ProcurementPlan procurementPlan : regionsOne) {
                listGroupSku.add(procurementPlan.getProduct().getProductSku());
            }
            // 获取组合商品信息
            List<Product> productList = this.productMapper.selectLinkListGroupBySku(listGroupSku, listGroupSku.get(CheckoutUtil.TYPE_ZERO));
            // 遍历组合商品表信息
            for (Product product : productList) {
                // 遍历组合商品的组成商品集合
                for (ProductGroup productGroup : product.getProductGroupList()) {
                    ProcurementPlanEasyExcelDerive procurementPlanEasyExcelDerive = new ProcurementPlanEasyExcelDerive();
                    procurementPlanEasyExcelDerive.setProductSku(product.getProductSku());
                    procurementPlanEasyExcelDerive.setProductSkuTwo(productGroup.getProductParentSku());
                    procurementPlanEasyExcelDerive.setProductNameCn(productGroup.getProductParentName());
                    procurementPlanEasyExcelDerive.setPurchasePrice(productGroup.getPurchasePrice());
                    procurementPlanEasyExcelDerive.setProviderName(productGroup.getProviderName());
                    // 遍历采购呢计划信息
                    for (ProcurementPlan procurementPlan : regionsOne) {
                        if (procurementPlan.getProduct().getProductSku().equals(product.getProductSku())) {
                            procurementPlanEasyExcelDerive.setProcurementPlanStore(procurementPlan.getProcurementPlanStore());
                            // 采购计划组合商品数量 = 采购数量 * 组合商品的组成商品的数量
                            procurementPlanEasyExcelDerive.setProcurementPlanCount(productGroup.getProductParentCount() * procurementPlan.getProcurementPlanCount());
                            procurementPlanEasyExcelDerive.setUsername(procurementPlan.getUsername());
                            procurementPlanEasyExcelDerive.setProcurementPlanSn(procurementPlan.getProcurementPlanSn());
                            procurementPlanEasyExcelDerive.setProcurementPlanDesc(procurementPlan.getProcurementPlanDesc());
                        }
                    }
                    list.add(procurementPlanEasyExcelDerive);
                }
            }
        }
        return list;
    }

    public int updateByPrimaryKeySelective(ProcurementPlan record) {
        return procurementPlanMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(ProcurementPlan record) {
        return procurementPlanMapper.updateByPrimaryKey(record);
    }

    // 批量删除
    public int updateByIdList(List<Integer> list) {
        List<ProcurementPlan> procurementPlanList = new ArrayList<>();
        for (Integer integer : list) {
            ProcurementPlan procurementPlan = new ProcurementPlan();
            procurementPlan.setId(integer);
            procurementPlan.setUpdateTime(LocalDateTime.now());
            procurementPlan.setDeleted(true);
            procurementPlanList.add(procurementPlan);
        }
        return procurementPlanMapper.updateByIdList(procurementPlanList);
    }

    /**
     * 同意采购
     * @param list 采购计划id集合
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateById(List<Integer> list,Integer adminId) {
        // 获取操作人员ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 生成操作日志
        Admin admin = this.adminService.findById(adminId);
        // 日志集合
        List<Log> logList = new ArrayList<>();
        for (Integer procurementPlanId : list) {
            Log log = new Log();
            log.setAdmin(admin.getUsername());
            log.setIp(IpUtil.getIpAddr(request));
            log.setType(procurementPlanId);
            log.setComment(TypeStateUtil.procurementPlanState_Ok_Desc);
            log.setAction(TypeStateUtil.procurementPlanState_Two_Desc);
            log.setAddTime(LocalDateTime.now());
            log.setUpdateTime(LocalDateTime.now());
            log.setDeleted(false);
            logList.add(log);
        }
        this.logService.addList(logList);
        // 采购计划集合
        List<ProcurementPlan> listOne = new ArrayList<>();
        // 修改采购计划状态
        for (Integer procurementPlanId : list) {
            ProcurementPlan procurementPlan = new ProcurementPlan();
            procurementPlan.setId(procurementPlanId);
            procurementPlan.setProcurementPlanState(TypeStateUtil.procurementPlanState_Two);
            procurementPlan.setUpdateTime(LocalDateTime.now());
            listOne.add(procurementPlan);
        }
        return procurementPlanMapper.updateByIdList(listOne);
    }

    /**
     * 拒绝采购/批量拒绝采购
     * @param list
     * @param desc
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateRefuseById(List<Integer> list,String desc,Integer adminId) {
        // 获取操作人员ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 生成操作日志
        Admin admin = this.adminService.findById(adminId);
        List<Log> logList = new ArrayList<>();
        for (Integer procurementPlanId : list) {
            Log log = new Log();
            log.setAdmin(admin.getUsername());
            log.setIp(IpUtil.getIpAddr(request));
            log.setComment(desc);
            log.setType(procurementPlanId);
            log.setAction(TypeStateUtil.procurementPlanState_Three_Desc);
            log.setDeleted(false);
            logList.add(log);
        }
        this.logService.addList(logList);
        // 采购计划集合
        List<ProcurementPlan> listOne = new ArrayList<>();
        // 修改采购计划状态
        for (Integer procurementPlanId : list) {
            ProcurementPlan procurementPlan = new ProcurementPlan();
            procurementPlan.setId(procurementPlanId);
            procurementPlan.setProcurementPlanState(TypeStateUtil.procurementPlanState_Three);
            procurementPlan.setUpdateTime(LocalDateTime.now());
            listOne.add(procurementPlan);
        }
        return procurementPlanMapper.updateByIdList(listOne);
    }


    /**
     * 重新修改
     * @param procurementPlanId 采购计划id
     * @param procurementPlanCount 采购数量
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateByIdTwo(Integer procurementPlanId,Integer procurementPlanCount,Integer adminId) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 生成操作日志
        Admin admin = this.adminService.findById(adminId);
        Log log = new Log();
        log.setAdmin(admin.getUsername());
        log.setIp(IpUtil.getIpAddr(request));
        log.setType(procurementPlanId);
        log.setComment(TypeStateUtil.procurementPlanState_Update_Desc);
        log.setAction(TypeStateUtil.procurementPlanState_One_Desc);
        log.setDeleted(false);
        this.logService.add(log);
        // 修改采购计划状态
        ProcurementPlan procurementPlan = new ProcurementPlan();
        procurementPlan.setId(procurementPlanId);
        procurementPlan.setProcurementPlanCount(procurementPlanCount);
        procurementPlan.setProcurementPlanState(TypeStateUtil.procurementPlanState_One);
        procurementPlan.setUpdateTime(LocalDateTime.now());
        return procurementPlanMapper.updateByPrimaryKeySelective(procurementPlan);
    }

}
